package com.ruoyi.cloudpc.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 单号生成器
 * @author Ten
 */
@Component
public class SequenceGenerator {

    private static final String REDIS_KEY = "sequence:counter";
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmdd");

//    @Value("${spring.redis.host}")
//    private String redisHost;
//    @Value("${spring.redis.port}")
//    private int redisPort;
//    private final JedisPool jedisPool;

//    public SequenceGenerator(String redisHost, int redisPort) {
//        this.jedisPool = new JedisPool(redisHost, redisPort);
//    }
//    public SequenceGenerator() {
//        this.jedisPool = new JedisPool(redisHost, redisPort);
//    }

    public String generateNumber() {
        // 8位日期前缀
        String datePart = LocalDateTime.now().format(DATE_FORMAT);

//        try (Jedis jedis = jedisPool.getResource()) {
//            // Redis原子计数器获取6位序列号
//            long sequence = jedis.incr(REDIS_KEY);
//            String seqPart = String.format("%06d", sequence % 1_000_000);
//
//            // 2位随机后缀防冲突
//            String randomPart = String.format("%02d", (int)(Math.random() * 100));
//
//            return datePart + seqPart + randomPart; // 总长度16位
//        }
            String randomPart = String.format("%02d", (int)(Math.random() * 100));
            return datePart + randomPart; // 总长度16位
    }

//    public static void main(String[] args) {
//        SequenceGenerator generator = new SequenceGenerator("43.137.14.73", 6379);
//        for (int i = 0; i < 100; i++) {
//            System.out.println(generator.generateNumber()); // 示例输出：2025092000001234
//        }
//    }
}
